package com.gmcloud.common.security.service;

import com.gmcloud.common.core.constant.CacheConstants;
import com.gmcloud.common.core.constant.SecurityConstants;
import com.gmcloud.common.utils.R;
import com.gmcloud.common.security.entity.GmUser;
import com.gmcloud.upms.api.system.entity.dto.UserInfo;
import com.gmcloud.upms.api.system.feign.RemoteUserService;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author zl.sir
 * @version 1.0
 * @since 2022/8/17 18:01
 */
@Service
public class GmUserDetailsServiceImpl implements GmUserDetailsService {

    private final CacheManager cacheManager;

    private final RemoteUserService remoteUserService;

    public GmUserDetailsServiceImpl(CacheManager cacheManager, RemoteUserService remoteUserService) {
        this.cacheManager = cacheManager;
        this.remoteUserService = remoteUserService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //  缓存查询是否存在用户详情，存在就直接获取缓存
        Cache cache = cacheManager.getCache(CacheConstants.USER_DETAILS);
        if (cache != null && cache.get(username) != null) {
            return (GmUser) Objects.requireNonNull(Objects.requireNonNull(cache.get(username), "用户缓存为null").get(), "用户缓存为null");
        }

        // 远程调用upms服务获取用户详情
        R<UserInfo> r = remoteUserService.info(username, SecurityConstants.FROM_IN);
        // 组装UserDetails
        UserDetails userDetails = getUserDetails(r);

        if (cache != null) {
            cache.put(username, userDetails);
        }
        return userDetails;
    }

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE;
    }
}
